package com.code.god.mysql.controller;

import cn.hutool.core.util.StrUtil;
import com.code.god.mysql.init.InitObject;
import com.code.god.mysql.template.R;
import com.code.god.mysql.util.ConnectionObject;
import com.code.god.mysql.util.MysqlUtil;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;

import static com.code.god.mysql.init.InitObject.CONNECTIONS;

@RestController
@RequestMapping("/connection")
public class ConnectionController {


    @GetMapping("/connectionMysql")
    public R connectionMysql(ConnectionObject param) {
        ConnectionObject connectionObject = CONNECTIONS.get(param.getConnectionName());
        if (connectionObject == null) {
            try {
                MysqlUtil.createConnect(param);
            } catch (Exception e) {
                e.printStackTrace();
                return R.failed(e);
            }
        }
        return R.ok();
    }

    @PostMapping("/new")
    public R newConnection(ConnectionObject param) {
        try {
            MysqlUtil.createConnect(param);
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed(e);
        }

        return R.ok("连接创建成功");
    }


    /**
     * 获取数据库集合
     * @param param
     * @return
     */
    @GetMapping("/listDatabases")
    public R listDatabases(ConnectionObject param) throws Exception {
        ConnectionObject connectionObject = CONNECTIONS.get(param.getConnectionName());
        if (connectionObject != null){
            Connection connection =  connectionObject.getDataSource().getConnection();
            return R.ok(MysqlUtil.listDatabaes(connection));
        }
        return R.failed();
    }
}
